<?php

/**
 * Albireo Kernel
 *
 * @copyright  Copyright (c) 2010 Albireo Solutions
 * @package    Kernel
 */

namespace KernelModule;

use Nette\Object;
use Nette\Web\IUser;
use Nette\Application\Application;
use Albireo\Mode;

/**
 * SingModel
 *
 * @author Albireo Solutions
 */
class SignModel extends Object {

    public function signOut(IUser $user, $clearIdentity = true) {
        return $user->logout($clearIdentity);
        //$redirectPresenter->redirect()
    }

    public function signIn(IUser $user, array $values) {
        if (Mode::isCritical()) {
            $user->setAuthenticationHandler(new KernelMasterAuthenticator());
        }

        //TODO: FILTHY!!! refactor
        $app = \Nette\Environment::getApplication()->getPresenter();
        // Nette changes session token itself (recommended by ISO/IEC 27002)
        $user->login($values['username'], $values['password']);
        if (substr($values['redirect'], 0, 1) == ":") {
            $resource = substr($values['redirect'], 1);
        }
        $privilege = substr($resource, strrpos($resource, ":") + 1);
        $resource = substr($resource, 0, strrpos($resource, ":"));
        //TODO: uncomment
        if ($user->isAllowed($resource, $privilege)) {
            $app->redirect($values['redirect']);
        } else {
//            $this->signOut($user);
            $app->flashMessage(_("You do not have enough rights to log in to Kernel."));
            $app->redirect(":Kernel:SignIn:");
        }
    }

}